package com.example.springboot01.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.springboot01.entity.User;
import com.example.springboot01.model.LoginStatusModel;
import com.example.springboot01.req.LoginEntity;
import com.example.springboot01.resp.Response;
import com.example.springboot01.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.List;

@RestController
@RequestMapping("/api/v1")
@Api(tags = "登录控制器", value = "登录控制器")
public class LoginController {


    @Resource
    private UserService userService;

    @PostMapping("/login")
    @ApiOperation("登录")
    public Response doLogin2(@RequestBody LoginEntity entity, HttpSession session){
        User user = userService.getOne(new LambdaQueryWrapper<User>()
                .eq(User::getUsername, entity.getUsername())
        );
        if (user == null) {
            return Response.error(null).setMsg("账号不存在");
        }

        if (!entity.getPassword().equals(user.getPassword())) {
            return Response.error(null).setMsg("密码不正确");
        }
        LoginStatusModel model = new LoginStatusModel(user.getId(), user.getUsername(), user.getUserType());
        return Response.ok(model).setMsg("登录成功");
    }


    @PostMapping("/register")
    public Response doRegister(@RequestBody User entity){
        List<User> list = userService.list(new LambdaQueryWrapper<User>()
                .eq(User::getUsername, entity.getUsername())
        );
        if (!CollectionUtils.isEmpty(list)) {
            return Response.error(null).setMsg("账号已被注册");
        }
        userService.save(entity);
        return Response.ok(null).setMsg("注册成功");
    }
}
